/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package presentation.controller.servlet;

import presentation.controller.servlet.*;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Properties;
import java.util.UUID;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.mail.AuthenticationFailedException;
import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import data.DAO.UserActivationDAO;
import data.DAO.UserDAOServiceImpl;
import model.entity.User;

/**
 *
 * @author ninkuhack: đăng ký cho khách, update user vào csdl
 * Hùng thực hiện
 */
@WebServlet(name = "SignUpServlet", urlPatterns = {"/SignUpServlet"})
public class SignUpServlet extends HttpServlet {

    /**
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
     * methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        final String succ = "/success.jsp";
        final String err = "/error.jsp";
        String email = request.getParameter("email");
        String fullname = request.getParameter("fullname");
        String passwrd = request.getParameter("password");
        User user = new User();
        user.setEmail(email);
        user.setFullName(fullname);
        user.setPassword(passwrd);
        user.setAddress(null);
        user.setBirthday(null);
        user.setCity(null);
        user.setImage(null);
        user.setPhone(null);
        user.setPoint(0);
        user.setRole(0);
        user.setStatus(0);
        UserDAOServiceImpl uDao = new UserDAOServiceImpl();
        if(uDao.createUser(user) == true){
            UUID uuid = UUID.randomUUID();
            User user1 = new User();
            UserDAOServiceImpl udao1 = new UserDAOServiceImpl();
            UserActivationDAO uadao = new UserActivationDAO();
            user1 = udao1.getUserByEmail(email);
            int userID = user1.getUserID();
            String hashcode = uuid.toString();
            uadao.createUserActivation(hashcode, userID);
            sendActivation(email,hashcode,request,response);
            request.getRequestDispatcher(succ).forward(request, response);
        }
        else{
            request.getRequestDispatcher(err).forward(request, response);
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Handles the HTTP <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
//        signup(request, response);
        processRequest(request, response);
    }
    private void signup(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
        User user = new User();
        UserDAOServiceImpl userDAO = new UserDAOServiceImpl();
        user.setFullName(request.getParameter("fullname"));
        user.setEmail(request.getParameter("email"));
        user.setPhone(request.getParameter("phone"));
        user.setPassword(request.getParameter("password"));
        user.setAddress(null);
        user.setBirthday(null);
        user.setCity(null);
        user.setImage(null);
        user.setPoint(0);
        user.setRole(2);
        user.setStatus(0);
        if(userDAO.createUser(user) == true){
            request.setAttribute("fullname", request.getParameter("fullname"));
            getServletContext().getRequestDispatcher("/folder/profile.jsp").forward(request, response);
        }
        else{
            response.sendRedirect("/folder/signuperror.jsp");
        }
    }
    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

    private void sendActivation(String email,String hashcode,HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        final String succ = "/success.jsp";
        final String err = "/error.jsp";
        String query = "?email="+email+"&hashcode="+hashcode+"";
        final String ActiveLink = "http://localhost:8084/DaNangCuisine/activation"+query+"";
        String from = "cuisinedanang@gmail.com";
        String to = email;
        String subject = "Registration Confirmation";
        String message = "<p>Thanks for your sign up at Da Nang Cuisine. Please click this link for activation your account</p> <a href='"+ActiveLink+"'>"+ActiveLink+"</a>";
        String login = "cuisinedanang@gmail.com";
        String passwrd = "Batch2015";
        try {
            Properties props = new Properties();
            props.setProperty("mail.host", "smtp.gmail.com");
            props.setProperty("mail.smtp.port", "587");
            props.setProperty("mail.smtp.auth", "true");
            props.setProperty("mail.smtp.starttls.enable", "true");
            
            Authenticator auth = new SMTPAuthenticator(login,passwrd);
            Session session = Session.getInstance(props, auth);
            MimeMessage msg = new MimeMessage(session);
            msg.setContent(message,"text/html");
            msg.setFrom(new InternetAddress(from));
            msg.setSubject(subject);
            msg.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
            Transport.send(msg);
        }  catch (AuthenticationFailedException ex) {
            request.setAttribute("ErrorMessage", "Authentication Failed");
            request.getRequestDispatcher(err).forward(request, response);
        } catch (MessagingException ex) {
            
            request.setAttribute("ErrorMessage", ex.getMessage());
            request.getRequestDispatcher(err).forward(request, response);
        }
        request.getRequestDispatcher(succ).forward(request, response);
    }

    private static class SMTPAuthenticator extends Authenticator {

        private PasswordAuthentication authentication;
        public SMTPAuthenticator(String login, String passwrd) {
            authentication = new PasswordAuthentication(login, passwrd);
        }
        protected PasswordAuthentication getPasswordAuthentication(){
            return authentication;
        }
    }

}
